//package cn.xspace.wnx.service;
//
//import android.app.AlarmManager;
//import android.app.PendingIntent;
//import android.app.Service;
//import android.content.BroadcastReceiver;
//import android.content.Context;
//import android.content.Intent;
//import android.net.ConnectivityManager;
//import android.os.Handler;
//import android.os.IBinder;
//import android.text.TextUtils;
//
//import com.xspace.android.xafcommon.appliction.BaseApplication;
//import com.xspace.android.xafcommon.util.AppUtils;
//import com.xspace.android.xafcommon.util.Constants;
//import com.xspace.android.xafcommon.util.EventBusConstant;
//import com.xspace.android.xafcommon.util.LogUtil;
//import com.xspace.android.xafcommon.util.PreferencesUtils;
//
//import org.jivesoftware.smack.ConnectionListener;
//import org.jivesoftware.smack.PacketListener;
//import org.jivesoftware.smack.XMPPConnection;
//import org.jivesoftware.smack.packet.Message;
//import org.jivesoftware.smack.packet.Packet;
//import org.jivesoftware.smack.packet.Presence;
//import org.jivesoftware.smackx.OfflineMessageManager;
//
//import java.util.HashMap;
//
//import cn.xspace.library.util.MyInfoUtil;
//import cn.xspace.wnx.xmpp.XmppConnectionManager;
//import de.greenrobot.event.EventBus;
//import rx.Observable;
//import rx.Subscriber;
//import rx.functions.Action1;
//import rx.schedulers.Schedulers;
//
///**
// * XMPP 推送的服务
// *
// * @author
// */
//public class IMChatService extends Service {
//
//    private static final String TAG = IMChatService.class.getSimpleName();
//    public static boolean hasNet = false;
//    public static boolean isConnection = false;
//    //是否初始化完毕,解决消息列表页面在没初始化完毕时调判断isConnection为false,在消息列表页面显示服务区压力大的Bug
//    public static boolean isSetUp = false;
//    private Context mContent;
//    private PendingIntent pendingIntent;
//    private XMPPConnection connection;
//    private XmppConnectListener mConnectListener;
//
//    /**
//     * 网络状态的EventBusBus事件
//     */
//    private HashMap<String, Object> event = new HashMap<>();
//
//    BroadcastReceiver reConnectionBroadcastReceiver = new BroadcastReceiver() {
//
//        @Override
//        public void onReceive(Context context, Intent intent) {
//            String action = intent.getAction();
//            if (action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
//                if (AppUtils.isConnected(mContent)) { //有网络
//                    event.put(EventBusConstant.TYPE, EventBusConstant.CONNECTION_INFO);
//                    event.put(EventBusConstant.CONNECTION_INFO, EventBusConstant.NETWORK_ONLINE);
//                    EventBus.getDefault().post(event);
//                    connectXmpp();
//                    hasNet = true;
//                } else { //断网了
//                    event.put(EventBusConstant.TYPE, EventBusConstant.CONNECTION_INFO);
//                    event.put(EventBusConstant.CONNECTION_INFO, EventBusConstant.NETWORK_OFFLINE);
//                    EventBus.getDefault().post(event);
//                    hasNet = false;
//                }
//            }
//        }
//    };
//
//    @Override
//    public void onCreate() {
//        LogUtil.d("onCreate");
//        mContent = this;
//        super.onCreate();
//        connection = XmppConnectionManager.getInstance().getConnection();
//        mConnectListener = new XmppConnectListener(mContent);
//        connection.addConnectionListener(mConnectListener);
////        setAlarmCheckService(60 * 1000);//取消XMPP服务
//        //动态注册网络状态监听的广播接受者
////        IntentFilter mFilter = new IntentFilter();
////        mFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
////        registerReceiver(reConnectionBroadcastReceiver, mFilter);
//    }
//
//    private void setAlarmCheckService(long interval) {
//        LogUtil.d(TAG, "wubaojie>>>" + "setAlarmCheckService: 定时器打开");
//        AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
//        Intent intent = new Intent();
//        intent.setAction("com.im.XmppConnectCheckBroad");
//        pendingIntent = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//        alarm.setRepeating(AlarmManager.RTC, System.currentTimeMillis() + interval, interval, pendingIntent);
//    }
//
//
//    @Override
//    public int onStartCommand(Intent intent, int flags, int startId) {
//        LogUtil.d(TAG, "wubaojie>>>" + "onStartCommand: 定时器调用了服务");
//        connectXmpp();
//        return super.onStartCommand(intent, flags, startId);
//    }
//
//    private void connectXmpp() {
//        if (AppUtils.isConnected(this)) {
//            hasNet = true;
//            connectServerOb()
//                    .subscribeOn(Schedulers.io())
//                    .subscribe(new Action1<Boolean>() {
//                        @Override
//                        public void call(Boolean aBoolean) {
//                            LogUtil.d(TAG, "wubaojie>>>" + "XMpp连接result >>" + (aBoolean ? "成功" : "失败"));
//                            isSetUp = true;
//                        }
//                    });
//        }
//    }
//
//    Observable<Boolean> connectServerOb() {
//        return Observable.create(new Observable.OnSubscribe<Boolean>() {
//            @Override
//            public void call(Subscriber<? super Boolean> subscriber) {
//                subscriber.onNext(connectServer());
//            }
//        });
//    }
//
//    /**
//     * 连接xmpp server
//     */
//    public synchronized boolean connectServer() {
////        if (isConnection) {
////            //已经是连接状态,返回true
////            LogUtil.d(TAG, "wubaojie-->IMChatService*************已经连接*************");
////            connection.sendPacket(new Presence(Presence.Type.available));
////            return true;
////        }
//        if (BaseApplication.mInstance != null && !BaseApplication.mInstance.isAccountConfigured()) {
//            return false;
//        }
//        LogUtil.e(TAG, "wubaojie-->" + connection.isConnected() + ":" + connection.isSocketClosed());
//        try {
//            if (connection.isConnected() && !connection.isSocketClosed()) {
//                LogUtil.d(TAG, "wubaojie-->*************已经连接*************");
//                connection.sendPacket(new Presence(Presence.Type.available));
//            } else {
//                LogUtil.d(TAG, "wubaojie-->*************开始连接*************");
//                connection.connect();
//            }
//            if (!connection.isAuthenticated()) {
//                String userid = MyInfoUtil.getMyUserid(mContent);
//                String pasword = AppUtils.MD5((String) PreferencesUtils.getPfValue(BaseApplication.mInstance, Constants
//                        .ACCOUNT_PASSWORD_KEY, String.class.getName()), false);
//
//                LogUtil.d(TAG, "wubaojie-->*************开始登录*************");
//                connection.login(userid, pasword, XmppConnectionManager.ACCOUNT_RESOURCE_KEY); // 登录
//                connection.sendPacket(new Presence(Presence.Type.available));
////                PingManager.getInstanceFor(connection).setPingIntervall(30);
////                PingManager.getInstanceFor(connection).ping("1");
////                PingManager.getInstanceFor(connection).registerPingFailedListener(new PingFailedListener() {
////                    @Override
////                    public void pingFailed() {
////                        LogUtil.e(TAG, "wubaojie>>>" + "pingFailed: ");
////                        T.showSingleL("心跳包发送失败");
////                    }
////                });
//                LogUtil.d(TAG, "wubaojie-->登录成功(mUserName:" + userid + ")" + "(mPassword:" + pasword + ")");
//            } else {
//                LogUtil.d(TAG, "wubaojie-->*************已经登录*************");
//            }
//            isConnection = true;
//            return true;
//        } catch (Exception e) {
//            e.printStackTrace();
//            LogUtil.e(TAG, "wubaojie>>>Exception:" + e.getMessage());
//            isConnection = TextUtils.equals(e.getMessage(), "Already logged in to server.");
//        }
//        return false;
//    }
////            System.setProperty("java.net.preferIPv4Stack", "true");
////            System.setProperty("java.net.preferIPv6Addresses", "false");
////            LogUtil.e(TAG, "wubaojie>>>" + "connectServer: isSocketClosed : " + connection.isSocketClosed());
////            if (connection.isConnected() && !connection.isSocketClosed()) {
////                LogUtil.d(TAG, "wubaojie-->IMChatService*************Already connected*************");
////            } else {
////                connection.connect();
////                connection.addConnectionListener(new XmppConnectListener(mContent));
////                LogUtil.d(TAG, "wubaojie-->IMChatService*************connect ok*************");
////            }
////            if (!connection.isAuthenticated()) {
////                String userid = MyInfoUtil.getMyUserid(mContent);
////                String pasword = AppUtils.MD5((String) PreferencesUtils.getPfValue(BaseApplication.mInstance, Constants
////                        .ACCOUNT_PASSWORD_KEY, String.class.getName()), false);
////                LogUtil.d(userid);
////                LogUtil.d(pasword);
////
////                connection.login(userid, pasword, XmppConnectionManager.ACCOUNT_RESOURCE_KEY); // 登录
////
////                connection.sendPacket(new Presence(Presence.Type.available));
////                PingManager.getInstanceFor(connection).setPingIntervall(30);
////                PingManager.getInstanceFor(connection).registerPingFailedListener(new PingFailedListener() {
////                    @Override
////                    public void pingFailed() {
////                        LogUtil.e(TAG, "wubaojie>>>" + "pingFailed: ");
////                        T.showSingleL("心跳包发送失败");
////                    }
////                });
////                LogUtil.d(TAG, "wubaojie-->IMChatService*************login*************");
////                LogUtil.d(TAG, "wubaojie-->IMChatService*************(mUserName:" + userid + ")" +
////                        "(mPassword:" + pasword + ")*************");
////            } else {
////                LogUtil.d(TAG, "wubaojie-->IMChatService*************Already login*************");
////            }
////            LogUtil.d(TAG, "wubaojie-->IMChatService*************login ok*************");
////            return true;
////        } catch (Exception e) {
////            e.printStackTrace();
////            LogUtil.d(TAG, "wubaojie-->IMChatService*************connectServer error*************");
////            if (e instanceof XMPPException) {
////                XMPPException xmppException = (XMPPException) e;
////                //XMPPError xmppError =null;
////                String errorMsg = xmppException.getMessage();
////                LogUtil.d(TAG, "wubaojie-->IMChatService*************xmppex:" + errorMsg + "*************");
////                //	xmppException.getXMPPError();
////                //if (xmppError != null && xmppError.getCondition() != null) {
////                //	LogUtils.i("ClientService*************xmppError.getCondition():" + xmppError.getCondition() +
////                // "*************");
////                //}
////                //if (xmppError != null && xmppError.getCondition() != null && xmppError.getCondition().equals
////                // (Condition.not_authorized.toString())) {
////                if (errorMsg.contains("SASLError") && errorMsg.contains("not-authorized")) {
////                    LogUtil.d(TAG, "wubaojie-->IMChatService*************用户名或密码错误*************");
////                } else {
////                    LogUtil.d(TAG, "wubaojie-->IMChatService*************登录失败*************");
////                }
////            } else {
////                LogUtil.d(TAG, "wubaojie-->IMChatService*************登录失败*************");
////            }
////            isConnection = false;
////        }
//
//
//    @Override
//    public IBinder onBind(Intent intent) {
//        return null;
//    }
//
//
//    @Override
//    public boolean onUnbind(Intent intent) {
//        return super.onUnbind(intent);
//    }
//
//    @Override
//    public void onDestroy() {
//        super.onDestroy();
////        if (connectionManager != null && connectionManager.isConnection()) {
////            connectionManager.disconnect();
////        }
//        cancelAlarm(this);
//        if (connection != null && connection.isConnected()) {
//            connection.disconnect();
//            connection.removeConnectionListener(mConnectListener);
//            isConnection = false;
//            PreferencesUtils.SaveBooleanData("LogoutNormal", false); //状态重置
//        }
////        unregisterReceiver(reConnectionBroadcastReceiver);
//        LogUtil.d(TAG, "wubaojie>>>" + "onDestroy>>>");
//    }
//
//    private void cancelAlarm(Context context) {
//        AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
//        if (pendingIntent != null) alarm.cancel(pendingIntent);
//        LogUtil.d(TAG, "wubaojie>>>" + "cancelAlarm:>>>");
//    }
//
//    class XmppConnectListener implements ConnectionListener {
//
//        private Context mContext;
//
//        XmppConnectListener(Context context) {
//            this.mContext = context;
//        }
//
//        @Override
//        public void connectionClosed() {
//            Boolean logoutNormal = PreferencesUtils.getBooleanData("LogoutNormal");
//            LogUtil.e(TAG, "wubaojie>>>" + "连接关闭: 是否正常退出?" + logoutNormal);
//            isConnection = false;
////            if (!logoutNormal) {
////                isConnection = false;
////                connectXmpp();
////                LogUtil.e(this, "wubaojie>>>" + "连接非正常关闭");
////            } else {
////                LogUtil.e(this, "wubaojie>>>" + "连接正常关闭");
////            }
//        }
//
//        @Override
//        public void connectionClosedOnError(Exception e) {
//            isConnection = false;
//            e.printStackTrace();
//            String eMsg = e.getMessage();
//            LogUtil.d(TAG, "wubaojie>>>connectionClosedOnError: " + eMsg);
//            if (eMsg.contains("conflict")) {
//                new Handler(mContext.getMainLooper()).post(new Runnable() {
//                    @Override
//                    public void run() {
////                        T.showSingleL("连接异常中断");
//                    }
//                });
//            } else if (eMsg.contains("ETIMEDOUT")) {
//            }
////            connectXmpp();
//            event.put(EventBusConstant.TYPE, EventBusConstant.CONNECTION_INFO);
//            event.put(EventBusConstant.CONNECTION_INFO, EventBusConstant.NETWORK_OVERLOAD);
//            EventBus.getDefault().post(event);
//
//        }
//
//        @Override
//        public void reconnectingIn(int i) {
//            LogUtil.e(TAG, "wubaojie>>>" + i + "秒后重新连接");
//        }
//
//        @Override
//        public void reconnectionSuccessful() {
//            LogUtil.e(TAG, "wubaojie>>>" + "服务器重新连接成功了");
//            isConnection = true;
//            event.put(EventBusConstant.TYPE, EventBusConstant.CONNECTION_INFO);
//            event.put(EventBusConstant.CONNECTION_INFO, EventBusConstant.NETWORK_RECONNECT);
//            EventBus.getDefault().post(event);
//        }
//
//        @Override
//        public void reconnectionFailed(Exception e) {
//            LogUtil.e(TAG, "wubaojie>>>" + "服务器断开连接了");
//            event.put(EventBusConstant.TYPE, EventBusConstant.CONNECTION_INFO);
//            event.put(EventBusConstant.CONNECTION_INFO, EventBusConstant.NETWORK_OVERLOAD);
//            EventBus.getDefault().post(event);
//        }
//
//    }
//
//    /******************************************************************************************/
//
//    private void initChatManager() {
//    }
//
//    /**
//     * 离线消息
//     *
//     * @param @param connection
//     * @return void
//     * @throws
//     * @Description: TODO
//     */
//    public void dealOfflineMsg(XMPPConnection connection) {
//        OfflineMessageManager offlineManager = new OfflineMessageManager(connection);
//        LogUtil.d(offlineManager.toString());
////        XmppOffLineMsg offLinemsg = XmppOffLineMsg.getInstance(mContent);
////        try {
////            Iterator<Message> it = offlineManager
////                    .getMessages();
////
////            LogUtil.d("离线消息数量>>" + offlineManager.getMessageCount());
////            while (it.hasNext()) {
////                Message message = it.next();
////                //保存离线消息
//////                if (!PreferencesUtils.getGoClassStatus(mContent)) {
//////                    Constant.offlineMsgs.add(message.getBody());
//////                }
////                LogUtil.d("xmpp msg>>" + message.getBody());
//////                offLinemsg.distributeOffLineMsg(message.getBody());
////            }
////            offlineManager.deleteMessages();
////        } catch (Exception e) {
////            e.printStackTrace();
////        }
//    }
//
//    PacketListener pListener = new PacketListener() {
//
//        @Override
//        public void processPacket(Packet arg0) {
//            Message message = (Message) arg0;
//            LogUtil.d("processPacket");
//            LogUtil.d(message + "");
//
//            if (message != null && message.getBody() != null
//                    && !message.getBody().equals("null")) {
////				Log.e("收到消息了", message.getBody());
//                LogUtil.d("msg>>" + message.getBody());
//                String acceptContent = message.getBody();
//                if (acceptContent.contains("class_teacher")) {
//                    LogUtil.d("start");
////					String[] server = acceptContent.split("&&");
////					String teachername = PreferencesUtils.getTeacherName(mContent);
////					if(teachername.equals("") || !teachername.equals(server[1]))
////					TEvent.trigger(Constant.CACHESERVICE, new Object[] { 0,
////							server[1] });
//                    return;
//                }
//            }
//        }
//
//    };
//    /**
//     *
//     * 发出Notification的method.
//     *
//     * @param iconId
//     *            图标
//     * @param contentTitle
//     *            标题
//     * @param contentText
//     *            你内容
//     * @param activity
//     * @author shimiso
//     * @update 2012-5-14 下午12:01:55
//     */
////	private void setNotiType(int iconId, String contentTitle,
////			String contentText, Class activity, String from) {
////
////		/*
////		 * 创建新的Intent，作为点击Notification留言条时， 会运行的Activity
////		 */
////		Intent notifyIntent = new Intent(this, activity);
////		notifyIntent.putExtra("to", from);
////		// notifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
////
////		/* 创建PendingIntent作为设置递延运行的Activity */
////		PendingIntent appIntent = PendingIntent.getActivity(this, 0,
////				notifyIntent, 0);
////
////		/* 创建Notication，并设置相关参数 */
////		Notification myNoti = new Notification();
////		// 点击自动消失
////		myNoti.flags = Notification.FLAG_AUTO_CANCEL;// 还有那个小组探究，ios那边没有用群组聊天
////		/* 设置statusbar显示的icon */
////		myNoti.icon = iconId;
////		/* 设置statusbar显示的文字信息 */
////		myNoti.tickerText = contentTitle;
////		/* 设置notification发生时同时发出默认声音 */
////		myNoti.defaults = Notification.DEFAULT_SOUND;
////		/* 设置Notification留言条的参数 */
////		myNoti.setLatestEventInfo(this, contentTitle, contentText, appIntent);
////		/* 送出Notification */
////		notificationManager.notify(0, myNoti);
////	}
//}
